package com.citywithincity.api.utils;

import javax.servlet.http.HttpServletRequest;

import com.citywithincity.api.entities.Customer;
import com.citywithincity.api.entities.Token;
import com.citywithincity.api.entities.UserId;
import com.citywithincity.cache.CacheUtil;
import com.citywithincity.utils.MD5Util;

public class AccessUtil {
	
	public static final int TOKEN_TIMEOUT = 20*60;
	
	public static final int USERID_TIMEOUT = (int) (86400L * 7);
	
	public static void initCustomer(Customer customer){
		
	}
	
	
	/**
	 * 
	 * @param request
	 * @param deviceID
	 * @param time
	 * @param userId userId不为空的情况下更新UserId
	 * @return
	 */
	public static Token createToken(HttpServletRequest request,String deviceID,Integer bTInteger,String userId,Customer customer){
		int time = bTInteger;
		if(time<0){
			time = -time;
		}
		StringBuilder sb = new StringBuilder(request.getRemoteAddr());
		String token = MD5Util.md5Appkey(sb.append(deviceID).append(String.valueOf(System.currentTimeMillis()*Math.random())).toString());
		String key = MD5Util.md5Appkey(sb.append(deviceID).append(String.valueOf(Math.random())).toString());
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
		customer.setKey(key);
		customer.setDevice(deviceID);
		customer.setToken(token);
		int beginIndex = time % 16;
		customer.setPinKey(key.substring(beginIndex, beginIndex +16));
		
		saveUser(customer);
		
		if(userId!=null){
			//保存用户id
			UserId id = new UserId();
			id.setToken(token);
			id.setDeviceId(deviceID);
			CacheUtil.set(userId, id,USERID_TIMEOUT);
		}
		
		
		Token result = new Token();
		result.setToken(token);
		result.setKey(key);
		result.setPinKey(customer.getRawPinKey());
		result.setHash(userId);
		request.setAttribute("time", time);
		request.setAttribute("customer", customer);
		return result;
	}

	public static void saveUser(Customer customer) {
		CacheUtil.set(customer.getToken(), customer,TOKEN_TIMEOUT);
	}
}
